﻿using AspectCore.DynamicProxy;
using AspectCore.Injector;
using RAP.Framework.Libary.DataSource.Model;
using RAP.Framework.Libary.Utils.Factory;
using System;
using System.Collections.Generic;
using System.Text;

namespace RAP.Framework.Libary.DataSource
{
  /// <summary>
  /// 数据实体生成器工厂对象
  /// </summary>
  public class DataModelGeneratorFactory : IDataModelGeneratorFactory
  {
    /// <summary>
    /// 数据实体代理对象生成器
    /// </summary>
    protected IProxyGenerator ProxyGenerator { get; set; }

    /// <summary>
    /// 
    /// </summary>
    protected ProxyGeneratorBuilder ProxyGeneratorBuilder { get; set; } = new ProxyGeneratorBuilder();

    /// <summary>
    /// 
    /// </summary>
    public DataModelGeneratorFactory()
    {
      ProxyGenerator = ProxyGeneratorBuilder.Build();
    }

    /// <summary>
    /// 配置工厂对象的参数，配置需要AOP拦截器以及拦截规则等等
    /// </summary>
    /// <param name="configureService">配置代理对象服务</param>
    public void Configure(Action<IServiceContainer> configureService)
    {
      ProxyGeneratorBuilder.ConfigureService(configureService);
    }

    /// <summary>
    /// 
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="args"></param>
    /// <returns></returns>
    public T CreateProxyClass<T>(params object[] args) where T : class
    {
      return (T)CreateProxyClass(typeof(T), args);
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="type"></param>
    /// <param name="args"></param>
    /// <returns></returns>
    public IDataModel CreateProxyClass(Type type, params object[] args)
    {
      return ProxyGenerator.CreateClassProxy(type, args) as IDataModel;
    }

    /// <summary>
    /// 释放资源
    /// </summary>
    public void Dispose()
    {
      ProxyGenerator?.Dispose();
    }
  }
}
